<template>
  <div class="all">
    <div class="class">
      <div class="class-header">
        <div class="header-left">
          <div class="line"></div>
          <div class="title">班级管理</div>
          <el-input
            v-model="classSearchInput"
            placeholder="请输入班级名称"
            style="width: 150px"
            class="className"
          ></el-input>
          <el-date-picker
            v-model="startDate"
            type="date"
            placeholder="选择开始时间"
            style="width: 150px"
            value-format="YYYY-MM-DD"
            class="className1"
          ></el-date-picker>
          <div class="line2"></div>
          <el-date-picker
            v-model="endDate"
            type="date"
            placeholder="选择结束时间"
            style="width: 150px"
            value-format="YYYY-MM-DD"
            class="className"
          ></el-date-picker>
          <div style="position: relative">
            <el-button @click="handleSearch" class="search">搜索</el-button>
            <img src="../../assets/images/搜索.png" class="searchImg" alt="" />
          </div>
        </div>
        <div class="header-right">
          <img
            src="../../assets/images/加号.png"
            class="addmsg"
            @click="handleAdd"
            v-if="user.roleId == '1' || user.roleId == '2'"
          />
        </div>
      </div>
    </div>

    <div class="class-content">
      <el-table :data="tableData" style="width: 100%">
        <el-table-column label="班级序号" align="center">
          <template #default="scope">
            {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="className" label="班级名称" align="center" width="230" />
        <el-table-column prop="people" label="班级人数" align="center" />
        <el-table-column prop="beginTime" label="开始时间" align="center" />
        <el-table-column prop="endTime" label="结束时间" align="center" />
        <el-table-column prop="classTeacher" label="班级老师" align="center" />
        <el-table-column prop="status" label="班级状态" align="center">
          <template #default="scope">
            <span :style="{ color: getStatusColor(scope.row.status) }">
              {{
                scope.row.status === 0
                  ? '未开班'
                  : scope.row.status === 1
                  ? '开班中'
                  : scope.row.status === 2
                  ? '已结课'
                  : scope.row.status
              }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="scoped">
            <el-button
              link
              type="success"
              @click="() => handleEdit(scoped.row)"
              v-if="user.roleId != '5'"
              >修改</el-button
            >
            <el-button link type="primary" @click="handleBusinessClassDetail(scoped.row)"
              >详情</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="page">
        <el-pagination
          background
          layout="prev, pager, next"
          :total="total"
          :page-size="pageSize"
          :current-page="currentPage"
          @current-change="handleCurrentChange"
        />
        <div>
          每页
          <el-input-number
            v-model="pageSize"
            :min="1"
            :max="30"
            controls-position="right"
            @change="handleChange"
          />条
        </div>
      </div>
    </div>

    <!-- 添加班级 -->
    <el-dialog v-model="dialogVisible" title="添加班级" width="400px" :show-close="false">
      <el-form
        :model="formData"
        :rules="rules"
        ref="formRef"
        label-width="100px"
        hide-required-asterisk
      >
        <el-row>
          <el-form-item label="班级名称" prop="className">
            <el-input v-model="formData.className" placeholder="请输入班级名称" />
          </el-form-item>
          <el-form-item label="开始时间" prop="beginTime">
            <el-date-picker
              v-model="formData.beginTime"
              type="date"
              placeholder="请选择开始时间"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="班级负责人" prop="teacherId">
            <el-select
              v-model="formData.teacherId"
              placeholder="请选择班级负责人"
              @change="handleTeacherChange"
            >
              <el-option
                v-for="(option, index) in classLeaderList"
                :key="index"
                :label="option.userName"
                :value="option.userId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="结束时间" prop="endTime">
            <el-date-picker
              v-model="formData.endTime"
              type="date"
              placeholder="请选择结束时间"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-row>
        <el-form-item label="学科" prop="courseName">
          <el-select v-model="formData.courseName" placeholder="请选择学科">
            <el-option
              v-for="option in subjectList"
              :key="option.courseId"
              :label="option.courseName"
              :value="option.courseName"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false" class="cancel">取消</el-button>
        <el-button type="primary" @click="handleConfirm" class="confirm">确认</el-button>
      </template>
    </el-dialog>
    <!-- 修改班级 -->
    <el-dialog v-model="dialogVisible2" title="修改班级" width="400px" :show-close="false">
      <el-form
        :model="formData2"
        :rules="rules2"
        ref="formRef2"
        label-width="100px"
        hide-required-asterisk
      >
        <el-row>
          <el-form-item label="班级名称" prop="className">
            <el-input v-model="formData2.className" />
          </el-form-item>
          <el-form-item label="开始时间" prop="beginTime">
            <el-date-picker
              v-model="formData2.beginTime"
              type="date"
              placeholder="请选择开始时间"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="班级负责人" prop="teacherId">
            <el-select
              v-model="formData2.teacherId"
              placeholder="请选择班级负责人"
              @change="ElditTeacher"
            >
              <el-option
                v-for="(option, index) in classLeaderList"
                :key="index"
                :label="option.userName"
                :value="option.userId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="结束时间" prop="endTime">
            <el-date-picker
              v-model="formData2.endTime"
              type="date"
              placeholder="请选择结束时间"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-row>
        <el-form-item label="学科" prop="courseName">
          <el-select v-model="formData2.courseName" placeholder="请选择学科">
            <el-option
              v-for="option in subjectList"
              :key="option.courseId"
              :label="option.courseName"
              :value="option.courseName"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible2 = false" class="cancel">取消</el-button>
        <el-button type="primary" @click="handleEdit1" class="confirm">修改</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
// import "../../assets/main.css"
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import {
  getClass,
  addClass,
  getClassLeaderList,
  getSubjectList,
  getClassByTeacherId,
} from '../api/Class'
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs' // 引入 dayjs 库

//本地存储
const user = JSON.parse(localStorage.getItem('user'))

// 总条目数
const total = ref(0)
// 每页显示的条目数量
const pageSize = ref(7)
// 当前页码
const currentPage = ref(1)
//数据
const tableData = ref([])
// 搜索条件
const classSearchInput = ref('')
const startDate = ref(null)
const endDate = ref(null)
//班级负责人
const classLeaderList = ref([])
//学科
const subjectList = ref([])

//获取数据
function fetchData(pageIndex, pageSize) {
  let data = {
    pageIndex,
    pageSize,
  }
  if (classSearchInput.value) {
    data.search = classSearchInput.value
  }
  if (startDate.value && endDate.value) {
    data.beginTime = startDate.value
    data.endTime = endDate.value
  }
  getClass('classList', data).then((res) => {
    if (res.code == 200) {
      tableData.value = res.dataset.classList
      total.value = res.dataset.pageCount * pageSize
    }
  })
}

//根据老师id获取班级
function fetchData1() {
  let data = {
    pageIndex: currentPage.value,
    pageSize: pageSize.value,
    teacherId: user.userId,
  }
  if (classSearchInput.value) {
    data.search = classSearchInput.value
  }
  if (startDate.value && endDate.value) {
    data.beginTime = startDate.value
    data.endTime = endDate.value
  }
  getClassByTeacherId('teacherClassById', data).then((res) => {
    if (res.code == 200) {
      tableData.value = res.dataset.teacherClassById
      total.value = res.dataset.pageCount * pageSize.value
    }
  })
}

//获取班级负责人
function ClassLeaderList() {
  getClassLeaderList('teacherList').then((res) => {
    if (res.code == 200) {
      classLeaderList.value = res.dataset
    }
  })
}

//获取学科
function SubjectList() {
  getSubjectList('courseList').then((res) => {
    if (res.code == 200) {
      subjectList.value = res.dataset.courseList
    }
  })
}

//获取数据
onMounted(() => {
  if (user.roleId == '3') {
    fetchData1()
  } else {
    fetchData(currentPage.value, pageSize.value)
  }
  ClassLeaderList()
  SubjectList()
})

//页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  if (user.roleId == '3') {
    fetchData1()
  } else {
    fetchData(currentPage.value, pageSize.value)
  }
}

const validateSearchTime = () => {
  if (startDate.value && endDate.value) {
    const start = dayjs(startDate.value)
    const end = dayjs(endDate.value)
    if (end.isBefore(start)) {
      ElMessage.warning('开始时间必须在结束时间之前')
      return false
    }
  }
  return true
}

// 搜索逻辑
const handleSearch = () => {
  if (!validateSearchTime()) {
    return
  }
  currentPage.value = 1 // 重置页码为1
  if ((startDate.value && endDate.value) || (!startDate.value && !endDate.value)) {
    if (user.roleId == '3') {
      fetchData1()
    } else {
      fetchData(currentPage.value, pageSize.value)
    }
  } else {
    ElMessage({
      message: '开始时间和结束时间必须全都有或者全都为空',
      type: 'warning',
    })
  }
}
//班级状态颜色
const getStatusColor = (status) => {
  if (status === 1) {
    return 'green'
  } else if (status === 0) {
    return 'black'
  } else if (status === 2) {
    return 'red'
  }
  return 'black'
}

// 详情
const router = useRouter()
const handleBusinessClassDetail = (row) => {
  // 详情逻辑
  //跳转到详情页面
  router.push({
    path: '/allTotal/ClassDetails',
    query: { classId: row.classId, status: row.status },
  })
}

// 添加班级模态框
// 新增：模态框显示状态
const dialogVisible = ref(false)
// 新增：表单数据
const formData = ref({
  className: '',
  beginTime: '',
  endTime: '',
  teacherId: '',
  classTeacher: '',
  courseName: '',
})
// 新增：表单引用
const formRef = ref(null)
// 新增：表单验证规则
const rules = ref({
  className: [{ required: true, message: '请输入班级名称', trigger: 'blur' }],
  beginTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
  endTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }],
  teacherId: [{ required: true, message: '请选择班级负责人', trigger: 'change' }],
  courseName: [{ required: true, message: '请选择学科', trigger: 'change' }],
})

// 新增：处理班级负责人选择
const handleTeacherChange = (value) => {
  const selectedTeacher = classLeaderList.value.find((teacher) => teacher.userId === value)
  if (selectedTeacher) {
    formData.value.classTeacher = selectedTeacher.userName
  }
}

//添加班级接口
function addClassData() {
  let data = {
    className: formData.value.className,
    beginTime: formData.value.beginTime,
    endTime: formData.value.endTime,
    teacherId: formData.value.teacherId,
    courseName: formData.value.courseName,
    classTeacher: formData.value.classTeacher,
  }
  addClass('addClass', data).then((res) => {
    if (res.code == 200) {
      ElMessage({
        message: '添加成功',
        type: 'success',
      })
      // 重置表单数据
      formData.value = {
        className: '',
        beginTime: '',
        endTime: '',
        teacherId: '',
        classTeacher: '',
        courseName: '',
      }
      fetchData(currentPage.value, pageSize.value) // 重新获取数据
    }
  })
}

// 新增：点击添加班级按钮方法
const handleAdd = () => {
  if (formRef.value) {
    formRef.value.clearValidate() // 清除表单验证
  }
  dialogVisible.value = true
}

// 新增：点击确认按钮方法
const handleConfirm = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      ElMessageBox.confirm('是否确认添加该班级？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          addClassData()
          dialogVisible.value = false // 关闭对话框
        })
        .catch(() => {
          ElMessage({
            type: 'info',
            message: '已取消添加',
          })
        })
    }
  })
}

// 修改班级模态框
// 修改：模态框显示状态
const dialogVisible2 = ref(false)
// 修改：表单数据
const formData2 = ref({
  classId: '',
  className: '',
  beginTime: '',
  endTime: '',
  teacherId: '',
  classTeacher: '',
  courseName: '',
})
// 修改：表单引用
const formRef2 = ref(null)
// 修改：表单验证规则
const rules2 = ref({
  className: [{ required: true, message: '请输入班级名称', trigger: 'blur' }],
  beginTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
  endTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }],
  teacherId: [{ required: true, message: '请选择班级负责人', trigger: 'change' }],
  courseName: [{ required: true, message: '请选择学科', trigger: 'change' }],
})
// 修改：点击修改按钮方法
const handleEdit = (row) => {
  formData2.value = { ...row }
  dialogVisible2.value = true
}

// 修改：处理班级负责人选择
const ElditTeacher = (value) => {
  const selectedTeacher = classLeaderList.value.find((teacher) => teacher.userId === value)
  if (selectedTeacher) {
    formData2.value.classTeacher = selectedTeacher.userName
  }
}

//修改班级接口
function EditClassData() {
  let data = {
    classId: formData2.value.classId,
    className: formData2.value.className,
    beginTime: formData2.value.beginTime,
    endTime: formData2.value.endTime,
    teacherId: formData2.value.teacherId,
    courseName: formData2.value.courseName,
    classTeacher: formData2.value.classTeacher,
  }
  addClass('updateClass', data).then((res) => {
    if (res.code == 200) {
      ElMessage({
        message: '修改成功',
        type: 'success',
      })
      if (user.roleId == '3') {
        fetchData1()
      } else {
        fetchData(currentPage.value, pageSize.value) // 重新获取数据
      }
      dialogVisible2.value = false // 关闭对话框
    }
  })
}

// 修改：点击确认按钮方法
const handleEdit1 = () => {
  formRef2.value.validate((valid) => {
    if (valid) {
      ElMessageBox.confirm('是否确认修改该班级？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          EditClassData()
        })
        .catch(() => {
          ElMessage({
            type: 'info',
            message: '已取消修改',
          })
        })
    }
  })
}

function handleChange() {
  currentPage.value = 1
  if (user.roleId == '3') {
    fetchData1()
  } else {
    fetchData(currentPage.value, pageSize.value)
  }
}
</script>

<style scoped>
:deep(.className .el-input__wrapper) {
  border-radius: 12px !important;
}
:deep(.className1 .el-input__wrapper) {
  border-radius: 12px !important;
}
.search {
  background-color: #0f6ab1;
  color: #fff;
  border: none;
  margin-left: 10px;
  border-radius: 16px;
  padding: 0;
  padding-right: 15px;
  padding-left: 36px;
}

/* 表格区域 */
.class-content {
  width: 90%;
  background-color: #fff;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

/* 表格数据 */
/* :deep(.el-table thead th) {
  background-color: #fbfcff !important;
} */
:deep(.el-table .cell) {
  color: black;
}
:deep(.details1) {
  margin-left: 55px;
}
/* 分页 */
.page {
  margin-top: 50px;
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
  align-items: center;
}
/* 分页背景色 */
:deep(.el-pager .is-active) {
  background-color: #0f6ab1 !important;
}

/* 模态框 */
:deep(.el-overlay .el-overlay-dialog) {
  position: absolute;
}
:deep(.el-overlay) {
  position: absolute;
}
:deep(.el-dialog) {
  padding: 0px;
  width: 800px;
}
:deep(.el-dialog header span) {
  display: inline-block;
  width: 100%;
  background-color: #0f6ab1;
  height: 40px;
  color: white;
  font-size: 15px;
  text-align: center;
  line-height: 40px;
}
:deep(.el-dialog__body) {
  display: flex;
  justify-content: center;
}
:deep(.el-select) {
  width: 200px;
}
:deep(.el-dialog__footer) {
  text-align: center;
  padding-bottom: 20px;
}
:deep(.confirm) {
  margin-left: 50px;
  background-color: #0f6ab1;
}
:deep(.cancel) {
  background-color: #0f6ab1;
  color: white;
}
</style>